<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="所属部门" prop="rrDeptName">
            <el-select
              v-model="queryParams.rrDeptName"
              placeholder="请输入所属部门"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            >
              <el-option
                v-for="dict in registrations"
                :key="dict.rrNo"
                :label="dict.rrDeptName"
                :value="dict.rrDeptName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="患者姓名" prop="rrPatientName">
            <el-input
              v-model="queryParams.rrPatientName"
              placeholder="请输入患者姓名"
              clearable
              size="small"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="挂号类型" prop="rrType">
            <el-select
              v-model="queryParams.rrType"
              placeholder="挂号类型"
              clearable
              size="small"
              style="width: 240px"
            >
            </el-select>
          </el-form-item>
          <el-form-item label="挂号时段" prop="rrTime">
            <el-input
              v-model="queryParams.rrTime"
              placeholder="挂号时段"
              clearable
              size="small"
              style="width: 240px"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="挂号状态" prop="rrStatus">
            <el-select
              v-model="queryParams.rrStatus"
              placeholder="挂号状态"
              clearable
              size="small"
              style="width: 240px"
            >
            </el-select>
          </el-form-item>
          <el-form-item label="挂号时间" prop="rrDate">
            <el-date-picker
              v-model="queryParams.rrDate"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="挂号时间"
            ></el-date-picker>
          </el-form-item>


          <el-table-column label="科室编码" align="center" key="rrDeptName" prop="deptCode" :show-overflow-tooltip="true" />
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>



        <el-table v-loading="loading" :data="registrationList" >

          <el-table-column label="流水编号" align="center" key="rrNo" prop="rrNo" />
          <el-table-column label="患者姓名" align="center" key="rrPatientName" prop="rrPatientName" :show-overflow-tooltip="true" />
          <el-table-column label="挂号科室" align="center" key="rrDeptName" prop="rrDeptName" :show-overflow-tooltip="true" />
          <el-table-column label="接诊医生" align="center" key="rrDoctor" prop="rrDoctor" :show-overflow-tooltip="true" />
          <el-table-column label="挂号费用" align="center" key="rrCharge" prop="rrCharge" width="120" />
          <el-table-column label="状态" align="center" key="rrStatus" prop="rrStatus"  width="80"></el-table-column>
          <el-table-column label="就诊时间" align="center" key="rrDate" prop="rrDate"  width="80"></el-table-column>
          <el-table-column label="挂号类型" align="center" key="rrType" prop="rrType"  width="80"></el-table-column>
          <el-table-column label="挂号时段" align="center" key="rrTime" prop="rrTime"  width="80"></el-table-column>


          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['registration:registration:edit']"
              >收费</el-button>
              <el-button
                v-if="scope.row.userId !== 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:hisdept:remove']"
              >退费</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-row>
          <el-col :span="12">
            <el-form-item label="收费状态" prop="rrStatus">
              <el-input v-model="form.rrStatus" placeholder="请输入科室编码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 认 收 费</el-button>
        <el-button @click="cancel">取 消 收 费</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  //import { listUser, getUser, delUser, addUser, updateUser, exportUser, resetUserPwd, changeUserStatus, importTemplate } from "@/api/system/user";
  import {listRegistration , getRegistration ,updateRegistration,listAllRegistrations} from '@/api/registration/regregistration'
  import { getToken } from "@/utils/auth";
  import { treeselect } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "User",
    components: { Treeselect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 挂号表格数据
        registrationList: null,
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        // 部门名称
        deptName: undefined,
        // 默认密码
        initPassword: undefined,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statusOptions: [],
        // 性别状态字典
        sexOptions: [],
        // 岗位选项
        postOptions: [],
        // 角色选项
        roleOptions: [],
          //自定义挂号列表集合
          registrations :[],
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/importData"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deptName: undefined,

          status: undefined
        },
        // 列信息
        columns: [
          { key: 0, label: `用户编号`, visible: true },
          { key: 1, label: `用户名称`, visible: true },
          { key: 2, label: `用户昵称`, visible: true },
          { key: 3, label: `部门`, visible: true },
          { key: 4, label: `手机号码`, visible: true },
          { key: 5, label: `状态`, visible: true },
          { key: 6, label: `创建时间`, visible: true }
        ],
        // 表单校验
        rules: {
          deptName: [
            { required: true, message: "科室名称不能为空", trigger: "blur" }
          ],
          deptPhone: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ]
        }
      };
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() { //页面加载执行(onload)
      this.getAllRegistrations();
      this.getList();
      this.getTreeselect();
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
      this.getDicts("sys_user_sex").then(response => {
        this.sexOptions = response.data;
      });
      this.getConfigKey("sys.user.initPassword").then(response => {
        this.initPassword = response.msg;
      });
    },
    methods: {
        // 查询所有挂号列表
        getAllRegistrations(){
            listAllRegistrations().then(resp => {
                this.registrations = resp.data;
            });
        },
      /** 查询挂号列表 */
      getList() {
        this.loading = true;
          listRegistration(this.queryParams).then(response => {
            this.registrationList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.rrId = data.id;
        this.getList();
      },
      // 菜单状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$confirm('确认要"' + text + '""' + row.userName + '"用户吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeUserStatus(row.userId, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          deptId: undefined,
          deptName: undefined,
          deptCode: undefined,
          deptLeader: undefined,
          deptPhone: undefined,
          password: undefined,
          orderNum: undefined,
          status: "0"
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.deptId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加科室";
        // this.getTreeselect();
        /*getUser().then(response => {
          this.postOptions = response.posts;
          this.roleOptions = response.roles;
          this.open = true;
          this.title = "添加用户";
          this.form.password = this.initPassword;
        });*/
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        // this.getTreeselect();
        const rrNo = row.rrNo ;
        getRegistration(rrNo).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改收费状态";
        });
      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(({ value }) => {
          resetUserPwd(row.userId, value).then(response => {
            this.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {});
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.rrId != undefined) {
                updateRegistration(this.form).then(response => {
                this.msgSuccess("成功收费");
                this.open = false;
                this.getList();
              });
            } else {
              addDept(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const deptIds = row.deptId || this.ids;
        this.$confirm('是否确认删除科室编号为"' + deptIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDepts(deptIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有用户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportUser(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate().then(response => {
          this.download(response.msg);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  };
</script>
